<?php
class Anderles_Form_Captcha_CaptchaCalc extends Zend_Captcha_Image
{
    protected function _generateWord()
    {
        $first = mt_rand(5, 9);
        return $first.(mt_rand(0, 1) ? '+':'-').mt_rand(1, $first - 1).'=';
    }

    public function render(Zend_View_Interface $view = null, $element = null)
    {
        return preg_replace('~<br\s*/?>~i', ' ', parent::render($view, $element));
    }

    public function isValid($value, $context = null)
    {
        if (!is_array($value) && !is_array($context)) {
            $this->_error(self::MISSING_VALUE);
            return false;
        }
        if (!is_array($value) && is_array($context)) {
            $value = $context;
        }

        $name = $this->getName();

        if (isset($value[$name])) {
            $value = $value[$name];
        }

        if (!isset($value['input'])) {
            $this->_error(self::MISSING_VALUE);
            return false;
        }
        $input = strtolower($value['input']);
        $this->_setValue($input);

        if (!isset($value['id'])) {
            $this->_error(self::MISSING_ID);
            return false;
        }

        $this->_id = $value['id'];

        $word = $this->getWord();
        list($first, $second) = split('[\+\-]{1}', rtrim($word, '='));
        $result = $first + (strpos($word, '-')!==false ? -$second:$second);
        if ($result !== (int)$input) {
            $this->_error(self::BAD_CAPTCHA);
            return false;
        }
        return true;
    }
}